from flask import Flask, make_response, jsonify, g, current_app as app,Blueprint,request
from sqlalchemy import select,insert,update,func,join
from sqlalchemy.sql import text
from eim.tools.dbtool import DBTool
from eim import db
from eim.result.simple_result import SimpleResult
from eim.tools.searchtool import SearchCondition,SearchConditionList,MatchLogic,PartnerRS

rolebp=Blueprint("rolebp","rolebp",__name__,url_prefix="/role")

@rolebp.route("/append",methods=["PUT"])
def appendNewRole():
    """
    增加新的角色信息
    """
    try:
        pms = request.json
        keys= pms.keys()
        if(not isinstance(pms,dict)):
            raise Exception("增加新角色时提交的信息格式不正确")
        if("rname" not in keys) or ("comment" not in keys):
            raise Exception("缺少必要的参数")
        if(pms["rname"]==""):
            raise Exception("角色名称不能为空")
        from eim.Services.roleService import RoleService
        rs = RoleService(db)
        id = rs.appendNewRole(pms["rname"],pms["comment"])
        return SimpleResult(status='T',value=id).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@rolebp.route("/upgrade/<int:id>",methods=["POST"])
def upgradeRole(id:int):
    """
    更新角色数据

    Args:
        id (int): 待更新的角色ID

    Raises:
        Exception: 参数错误异常
        Exception: 参数信息缺失异常

    Returns:
        _type_: 受影响行数
    """
    try:
        pms = request.json
        keys= pms.keys()
        if(not isinstance(pms,dict)):
            raise Exception("更新角色时提交的信息格式不正确")
        if("rname" not in keys) or ("comment" not in keys):
            raise Exception("缺少必要的更新参数")
        from eim.Services.roleService import RoleService
        rs = RoleService(db)
        rcnt = rs.upgradeRole(id,pms["rname"],pms["comment"])
        return SimpleResult(status='T',value=rcnt).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()

@rolebp.route("/getRoleByID/<int:id>",methods=["GET"])
def getRoleByID(id:int):
    """
    根据角色id获取角色信息

    Args:
        id (int): 角色id

    Returns:
        _type_: 返回携带角色信息的简单对象模型
    """         
    try:
        from eim.Services.roleService import RoleService
        rs = RoleService(db)
        res = rs.getOneByID(id)
        
        return SimpleResult(status='T',value=res).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@rolebp.route("/getRoleByCode/<code>",methods=["GET"])
def getRoleByCode(code:int):
    """
    根据角色编码获取角色信息

    Args:
        code (str): 角色code

    Returns:
        _type_: 返回携带角色信息的简单对象模型
    """         
    try:
        from eim.Services.roleService import RoleService
        rs = RoleService(db)
        res = rs.getOneByCode(code)
        return SimpleResult(status='T',value=res).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@rolebp.route("/pageRole_old/<int:pn>/<int:ps>",methods=["GET"])
def pageRole_old(pn:int,ps:int):
    """
    分页获取角色数据

    Args:
        pn (int): 分页页码
        ps (int): 分页页面尺寸
    """
    try:
        from eim.Services.roleService import RoleService
        rs = RoleService(db)
        res = rs.getRoleList(pn,ps)
        return SimpleResult(status='T',value=res).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()

@rolebp.route("/pageRole/<int:pn>/<int:ps>",methods=["POST"])
def pageRole(pn:int,ps:int):
    """
    分页获取角色信息

    Args:
        pn (int): 分页页码
        ps (int): 分页页面尺寸

    Returns:
        _type_: 分页结果
    """
    try:
        pms = request.json
        if(not isinstance(pms,dict)):
            raise Exception("请正确提交查询参数")
        if(not 'cols' in pms.keys()):
            raise Exception("参数中必须包含字段列表cols")
        if(not 'pms' in pms.keys()):
            raise Exception("参数中必须包含检索条件对象pms")
        
        slist = SearchConditionList()
        for item in pms["pms"]:
            cd = item["CD"]
            cdobj = SearchCondition(cd["field"],MatchLogic.from_Name(cd["logic"]),cd["value"])
            rs=PartnerRS.from_name(item["RS"])
            slist.appendCondition(rs,cdobj)
        
        from eim.Services.roleService import RoleService
        us = RoleService(db)
        
        res = us.pageRoles(pn,ps,pms["cols"],slist)
        return SimpleResult(status="T",value=res).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
  
@rolebp.route("/delete/<int:id>",methods=["DELETE"])
def deleteRoleByID(id:int):
    """
    删除指定id的角色数据

    Args:
        id (int): 角色id
    """
    try:
        from eim.Services.roleService import RoleService
        rs = RoleService(db)
        res = rs.deleteByID(id)
        return SimpleResult(status='T',value=res).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
 
@rolebp.route("/allRoles",methods=["GET"])    
def getAllRole():
    """
    获取所有角色
    """
    try:
        from eim.Services.roleService import RoleService
        rs = RoleService(db)
        res = rs.getAllRoles()
        return SimpleResult(status="T",value=res).toDict()
    except Exception as ex:
        info = str(ex)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()